<?php

namespace App\Http\Controllers;

use App\Models\RoomCheckIn;
use App\Models\Rooms;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RoomsCheckController extends BaseController
{
        public function index(Request $request){

        }

        public function store(Request $request): \Illuminate\Http\JsonResponse
        {

            $room_num = $request->get("room_num");
            $user_name = $request->get("user_name");
            $user_phone = $request->get("user_phone");
            $start_date = $request->get("start_date");
            $end_date = $request->get("end_date");
            if(!$room_num || !$user_name || !$user_phone || !$start_date || !$end_date){
                return Failed(10002, ["file" => "RoomsCheckController", "line" => __LINE__, "need_filed" => ['room_num', 'user_name', 'user_phone', 'end_date',]]);
            }

            $room_info = Rooms::where('room_num',$room_num)->first();

            if(!$room_info || $room_info->status!=1){
                return $this->fail(10002, "未查询到房间或房间不可用", ["file" => "GoodsController", "line" => __LINE__, "room_info" => $room_info]);
            }

            DB::beginTransaction();
            try {
                $room_check_in = new RoomCheckIn();
                $room_check_in->room_id = $room_info->id;
                $room_check_in->room_num = $room_num;
                $room_check_in->user_name = $user_name;
                $room_check_in->user_phone = $user_phone;
                $room_check_in->in_date = $start_date;
                $room_check_in->out_date = $end_date;
                $room_check_in->status = 0;
                $room_check_in->check_code = rand(100000,999999);
                $room_check_in->updated_at = date("Y-m-d H:i:s");
                $room_check_in->created_at = date("Y-m-d H:i:s");
                if(!$room_check_in->save()){
                    return $this->fail(10003, "入住登记记录保存失败", ["file" => "GoodsController", "line" => __LINE__, "room_info" => $room_info]);
                }
                $room_info->status = 2;
                $room_info->updated_at = date("Y-m-d H:i:s");
                if(!$room_info->save()){
                    return $this->fail(10003, "房间状态保存失败", ["file" => "GoodsController", "line" => __LINE__, "room_info" => $room_info]);
                }
            }catch (\Exception $exception){

                DB::rollBack();
                return $this->fail(10003, "入住登记记录保存失败", ["file" => "GoodsController", "line" => __LINE__, "room_info" => $room_info]);
            }
            DB::commit();
            return Success(10000, []);
        }

        public function update(Request $request,int $id){

        }

        public function destroy(int $id){

        }
}
